package ac.beiwo.baas.file.controller;

import ac.beiwo.baas.common.entity.SimpleError;
import ac.beiwo.baas.common.entity.SimpleResult;
import ac.beiwo.baas.file.entity.BaasFile;
import ac.beiwo.baas.file.entity.FileStoragePlatform;
import ac.beiwo.baas.file.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by Staryet on 15/8/13.
 */
@RestController
@RequestMapping(value = "/file")
public class FileController {

    @Autowired
    private FileService fileService;

    /**
     * 写入文件
     *
     * @param body
     * @return
     * @throws SimpleError
     */
    @RequestMapping(value = "/", method = RequestMethod.POST)
    @ResponseBody
    public SimpleResult insert(@RequestBody String body) throws SimpleError {
        SimpleResult result = SimpleResult.success();
        return result;
    }

    /**
     * 客户端请求上传文件所需要的鉴权信息
     *
     * @param fileName 文件名
     * @param platform 平台
     * @return 令牌
     */
    @RequestMapping(value = "/getToken", method = RequestMethod.GET)
    @ResponseBody
    public SimpleResult getToken(@RequestParam(required = true) String fileName,
                                 @RequestParam(required = true) String platform) throws SimpleError {
        FileStoragePlatform plat = FileStoragePlatform.get(platform);
        SimpleResult result = SimpleResult.success();
        result.putDataAll(fileService.getToken(plat, fileName));
        return result;
    }

    @RequestMapping(value = "/callback", method = RequestMethod.POST)
    @ResponseBody
    public Object callBack(@RequestBody String body, HttpServletRequest request) throws SimpleError {
        if (body.startsWith("platform=qiniu")) {
            //七牛的回调
            return fileService.callback(FileStoragePlatform.Qiniu, body, request);
        } else {
            return null;
        }
    }

}
